<template>
    <div ref="wrapper">
        <slot>
        </slot>
    </div>
</template>

<script type="text/ecmascript-6">
import BScroll from 'better-scroll'
export default {
    props:{
        probeType:{
            type:Number,
            default:1
        },
        click: {
            type:Boolean,
            default:true
        },
        data: {
            type:Array,
            default:null
        },
        listenScroll: {
            type:Boolean,
            default:false
        },
        pullup:{
            type:Boolean,
            default:false
        },
        beforeScroll:{
            type:Boolean,
            default:false
        },
        refreshDelay: {
            type:Number,
            default:30
        }
    },
    mounted() {
        setTimeout(()=>{
            this._initScroll()
        },20)
    },
    methods:{
        //初始化scroll
        _initScroll () {
            if(!this.$refs.wrapper){
                return
            }
            this.scroll= new BScroll(this.$refs.wrapper,{
                probeType:this.probeType,
                click:this.click
            })

            if(this.listenScroll){
                let me=this;

                //这个pos哪里来的
                this.scroll.on('scroll',(pos)=>{
                    me.$emit('scroll',pos)
                })
            }


            //上拉加载
            if(this.pullup) {
                this.scroll.on('scrollEnd',()=>{
                    console.log(this.scroll.y,this.scroll.maxScrollY)
                    if(this.scroll.y <= this.scroll.maxScrollY + 100){
                        this.$emit('scrollToEnd')
                    }
                })
            }

            // 滚动收起键盘
            if(this.beforeScroll){
                this.scroll.on('beforeScrollStart',()=>{
                    console.log('scroll滚动')
                    this.$emit('beforeScroll')
                })
            }
        },
        //启用scroll
        enable() {
            this.scroll && this.scroll.enable()
        },
        //禁用scroll
        disable() {
            this.scroll && this.scroll.disable()
        },
        refresh() {
            this.scroll && this.scroll.refresh()
        },
        //滚向指定位置
        scrollTo() {
            this.scroll && this.scroll.scrollTo.apply(this.scroll,arguments)
        },
        scrollToElement () {
            this.scroll && this.scroll.scrollToElement.apply(this.scroll,arguments)
        }
    },
    //观察数据变化
    watch:{
        data() {
            setTimeout(()=>{
                this.refresh()
            },this.refreshDelay)
        }
    }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

</style>


